package com.test.webscoket.main;

import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketSessionManager {

    // 存储客户端 ID 和对应的 WebSocketSession
    private final Map<String, Session> sessions = new ConcurrentHashMap<>();

    // 添加会话
    public void addSession(String clientId, Session session) {
        sessions.put(clientId, session);
    }

    // 移除会话
    public void removeSession(String clientId) {
        if (sessions.containsKey(clientId)) {
            Session session = sessions.get(clientId);
            try (Session remove = sessions.remove(clientId)) {
                session.close();
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
        }
    }

    // 获取会话
    public Session getSession(String clientId) {
        return sessions.get(clientId);
    }

    // 向指定客户端发送消息
    public void sendMessageToClient(String clientId, String message) throws IOException {
        Session session = getSession(clientId);
        if (session != null && session.isOpen()) {
            session.getBasicRemote().sendText(message);
        } else {
            System.out.println("Client " + clientId + " is not connected.");
        }
    }
}
